package com.itboye.lottery.retrofit.subscriber;

import android.util.Log;

import com.itboye.lottery.retrofit.ApiException;

import rx.Subscriber;


public class CommonSubscriber<T> extends Subscriber<T> implements CancelSubscriberListener {

    private SubscriberListener<T> mSubscriberListener;

    public CommonSubscriber(SubscriberListener mSubscriberListener) {
        this.mSubscriberListener = mSubscriberListener;
    }

    @Override
    public void onCompleted() {
    }

    /**
     * 对错误进行统一处理
     *
     * @param e Throwable
     */
    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e != null) {
            ApiException exception = (ApiException) e;
            if (exception.isTokenExpried()) {
                //TODO 处理token失效对应的逻辑    强制下线，，，
//                MyApplication.Companion.getInstance().removeAllActivity();
            } else {
                Log.e("", e.getMessage());
            }
//        HttpResponse<String> httpResponse = new HttpResponse(exception.getCode(), e.getLocalizedMessage(), exception.getLocalizedMessage());
            if (mSubscriberListener != null) {
                    mSubscriberListener.onError(((ApiException) e).getDisplayMessage(), exception.getCode());
            }
        }
    }

    /**
     * 将onNext方法中的返回结果交给Activity或Fragment自己处理
     *
     * @param t 创建Subscriber时的泛型类型
     */
    @Override
    public void onNext(T t) {
        if (mSubscriberListener != null) {
//            if (httpResponse.getCode() < 0) {
//                HttpResponse<String> httpResponse1=new HttpResponse<((HttpResponse) t).getData()>();
//                mSubscriberListener.onError(t, httpResponse.getCode());
//            } else {
//          if (EmptyUtils.isNotNull(t)) {
            mSubscriberListener.onNext((T) t);
//            }
//          }
        }
    }

    @Override
    public void onCancelSubscriber() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }
}